package cn.com.transfer.services;

import cn.com.transfer.params.IcbcParams;
import cn.com.transfer.utils.Constants;
import cn.com.transfer.utils.IcbcInfo;
import cn.com.transfer.utils.IcbcNative;
import flexjson.JSONSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static cn.com.transfer.utils.IcbcInfo.isRun;
import static cn.com.transfer.utils.IcbcInfo.schoolId;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 签到
 */
public class SignIn extends MsgHandlerService {
    private Logger logger = LoggerFactory.getLogger(SignIn.class);


    @Override
    public String handler(Map params) {
        Map rtn = new HashMap();
        try {
            Calendar ca = Calendar.getInstance();
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            Date start = format.parse(format.format(ca.getTime()).substring(0, 8) + IcbcInfo.start);
            Date end = format.parse(format.format(ca.getTime()).substring(0, 8) + IcbcInfo.end);
            checkArgument(ca.getTime().after(start) && ca.getTime().before(end), "未到系统签到时间");

            IcbcParams req = new IcbcParams(0);
            req.schoolCode = schoolId;
            req.transCode = Constants.ICBC_TRANS_SIGN_IN;
            req.transTime = String.format("%02d:%02d:%02d", ca.get(Calendar.HOUR_OF_DAY), ca.get(Calendar.MINUTE), ca.get(Calendar.SECOND));
            req.transDate = String.format("%04d-%02d-%02d", ca.get(Calendar.YEAR), ca.get(Calendar.MONTH) + 1, ca.get(Calendar.DAY_OF_MONTH));
            req.mac = req.genMac(0);

            IcbcParams resp = sendMessage(req);
            checkNotNull(resp, "连接服务器失败");
            checkArgument(resp.rtnCode.equals("00000"), resp.rtnMsg == null ? (String) Constants.msgMap.get(resp.rtnCode) : resp.rtnMsg);

            isRun = true;
            IcbcNative.setPkgKey(IcbcNative.decrypt(resp.pkgKey, 0));
            IcbcNative.setMacKey(IcbcNative.decrypt(resp.macKey, 0));
            rtn.put("success", true);
            logger.info("签到成功");
        } catch (Exception e) {
            logger.error("error in signIn", e);
            rtn.put("success", false);
            rtn.put("msg", e.getMessage() != null ? e.getMessage() : e.toString());
        }

        return new JSONSerializer().serialize(rtn);
    }
}
